<template>
    <div class="chart-container">
        <div ref="statusChartContainer" class="chart"></div>
        <div ref="orderChartContainer" class="chart"></div>
        <div ref="lineChartContainer" class="chart"></div>
    </div>
    <el-button style="margin-left: 40%; height: 200px; width: 400px;" @click="router.push('/')">返回上一级</el-button>
</template>

<script setup>
import { getTableList } from '@/api/dashed';  // 假设你是通过这个接口获取数据
import { onMounted, ref, nextTick } from 'vue';
import * as echarts from 'echarts';
import { orderList } from '@/api/order';
import { useRouter } from 'vue-router';
const router = useRouter()
// 定义 ref 用于绑定 DOM 元素
const statusChartContainer = ref(null);
const orderChartContainer = ref(null);
const lineChartContainer = ref(null);
const tableList = ref([]);
const statusChartInstance = ref(null);
const orderChartInstance = ref(null);
const lineChartInstance = ref(null);
const order = ref([]);

const getOrder = async () => {
    const { data } = await orderList();
    order.value = data.orderList;

    // 初始化订单图表
    nextTick(() => {
        initOrderChart();
        initLineChart();
    });
};

const getTable = async () => {
    const { data } = await getTableList();
    tableList.value = data;

    // 初始化设备状态图表
    nextTick(() => {
        initStatusChart();
    });
};

const processOrderData = () => {
    const rechargeData = {}; // 用于存储每天的充值数据
    const consumptionData = {}; // 用于存储每天的消费数据

    order.value.forEach(item => {
        const date = new Date(item.payment_time).toISOString().split('T')[0]; // 提取日期
        const amount = parseFloat(item.payment_price);

        if (item.table_number === null) {
            // 充值
            rechargeData[date] = (rechargeData[date] || 0) + amount;
        } else {
            // 消费
            consumptionData[date] = (consumptionData[date] || 0) + amount;
        }
    });

    return { rechargeData, consumptionData };
};

const initStatusChart = () => {
    // 获取DOM元素
    const chartDom = statusChartContainer.value;

    // 初始化ECharts实例
    statusChartInstance.value = echarts.init(chartDom);

    // 统计每种状态的数量
    const statusCounts = {
        "未使用": tableList.value.filter(item => item.status === 0).length,
        "正在使用": tableList.value.filter(item => item.status === 1).length,
        "正在预约中": tableList.value.filter(item => item.status === 2).length,
        "维修": tableList.value.filter(item => item.status === 3).length,
        "损坏": tableList.value.filter(item => item.status === 4).length,
    };

    // 准备图表数据
    const option = {
        title: {
            text: '设备状态分布',
            left: 'center'
        },
        tooltip: {
            trigger: 'item'
        },
        legend: {
            orient: 'vertical',
            left: 'left',
        },
        series: [
            {
                name: '数量',
                type: 'pie',
                radius: '50%',
                data: Object.entries(statusCounts).map(([key, value]) => ({
                    name: key,
                    value: value
                })),
                emphasis: {
                    itemStyle: {
                        shadowBlur: 10,
                        shadowOffsetX: 0,
                        shadowColor: 'rgba(0, 0, 0, 0.5)'
                    }
                }
            }
        ]
    };

    // 设置图表配置项和数据
    statusChartInstance.value.setOption(option);
};

const initOrderChart = () => {
    const chartDom = orderChartContainer.value;
    orderChartInstance.value = echarts.init(chartDom);

    const { rechargeData, consumptionData } = processOrderData();

    // 获取所有日期的列表并排序
    const dates = Array.from(new Set([...Object.keys(rechargeData), ...Object.keys(consumptionData)])).sort();

    // 为每个日期获取对应的充值和消费金额
    const rechargeSeries = dates.map(date => rechargeData[date] || 0);
    const consumptionSeries = dates.map(date => consumptionData[date] || 0);

    const option = {
        title: {
            text: '每日充值与消费情况',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['充值', '消费'],
            left: 'left'
        },
        xAxis: {
            type: 'category',
            data: dates,  // X轴的数据为日期
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '充值',
                type: 'bar',
                data: rechargeSeries,
                itemStyle: {
                    color: '#73c0de'
                }
            },
            {
                name: '消费',
                type: 'bar',
                data: consumptionSeries,
                itemStyle: {
                    color: '#ff7f50'
                }
            }
        ]
    };

    orderChartInstance.value.setOption(option);
};

const initLineChart = () => {
    const chartDom = lineChartContainer.value;
    lineChartInstance.value = echarts.init(chartDom);

    const { rechargeData, consumptionData } = processOrderData();

    // 获取所有日期的列表并排序
    const dates = Array.from(new Set([...Object.keys(rechargeData), ...Object.keys(consumptionData)])).sort();

    // 为每个日期获取对应的充值和消费金额
    const rechargeSeries = dates.map(date => rechargeData[date] || 0);
    const consumptionSeries = dates.map(date => consumptionData[date] || 0);

    const option = {
        title: {
            text: '每日充值与消费趋势',
            left: 'center'
        },
        tooltip: {
            trigger: 'axis'
        },
        legend: {
            data: ['充值', '消费'],
            left: 'left'
        },
        xAxis: {
            type: 'category',
            data: dates,  // X轴的数据为日期
        },
        yAxis: {
            type: 'value'
        },
        series: [
            {
                name: '充值',
                type: 'line',
                data: rechargeSeries,
                itemStyle: {
                    color: '#73c0de'
                }
            },
            {
                name: '消费',
                type: 'line',
                data: consumptionSeries,
                itemStyle: {
                    color: '#ff7f50'
                }
            }
        ]
    };

    lineChartInstance.value.setOption(option);
};

onMounted(() => {
    getTable();
    getOrder();
});

</script>

<style lang="scss" scoped>
.chart-container {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
    gap: 20px;
    padding: 20px;
}

.chart {
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    height: 400px;
    /* 限制图表的高度 */
    width: 100%;
    /* 宽度占满父容器 */
    overflow: hidden;
    /* 确保内容不会超出容器 */
}
</style>
